"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 二级分区
Case Name   : range_hash二级分区表:密态数据库
Create At   : 2022/2/24
Owner       : @daiguatutu
Description :
    1.配置全密态环境变量
    2.连接全密态数据库，分别创建cmk，cek
    3.创建表空间
    4.创建二级分区表，指定非分区列加密
    5.创建二级分区表，指定分区列加密
    6.清理环境
Expect      :
    1.配置成功
    2.成功
    3.成功
    4.合理报错
    5.合理报错
    6.清理成功
History     :
    -- @modify: modified by @daiguatutu at 2023/09/08 代码变更，
    RSA_2048不是安全算法，改用RSA_3072算法
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Subpartition(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.primaryNode = Node('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.mkdir_path = os.path.join(macro.DB_INSTANCE_PATH,
                                       'kms_subpartition_0310')
        self.env_bak = os.path.join(macro.DB_INSTANCE_PATH, 'env0001_bak')
        self.cmk = 'cmk_subpartition_0310'
        self.cek = 'cek_subpartition_0310'
        self.key_path = 'keypath_subpartition_0310'
        self.t_name = 't_subpartition_0310'
        self.ts_name = 'ts_subpartition_0310'

    def test_subpartition(self):
        text = '-----step1:配置全密态环境变量 expect:配置成功-----'
        self.log.info(text)
        conf_cmd = f'mkdir {self.mkdir_path};' \
            f'cp {macro.DB_ENV_PATH} {self.env_bak};' \
            f'sed -i \'$aexport LOCALKMS_FILE_PATH=' \
            f'{self.mkdir_path}\' {macro.DB_ENV_PATH};'
        self.log.info(conf_cmd)
        conf_msg = self.primaryNode.sh(conf_cmd).result()
        self.log.info(conf_msg)

        text = '-----step2:连接全密态数据库，分别创建cmk，cek，' \
               '查看表的cmk及cek相关信息 expect:成功-----'
        self.log.info(text)
        sql_cmd = f'''drop client master key if exists {self.cmk};
            create client master key {self.cmk} with
            (key_store=localkms,key_path="{self.key_path}",
            algorithm=rsa_3072);
            drop column encryption key if exists {self.cek} cascade;
            create column encryption key {self.cek} with values
            (client_master_key = {self.cmk},algorithm = 
            aead_aes_256_cbc_hmac_sha256);'''
        self.log.info(sql_cmd)
        msg = self.pri_sh.execut_db_sql(sql_cmd, sql_type='-C')
        self.log.info(msg)
        self.assertIn(self.constant.create_cmk_success, msg, '执行失败:' + text)
        self.assertIn(self.constant.create_cek_success, msg, '执行失败:' + text)

        text = '-----step3:创建表空间 expect:成功-----'
        self.log.info(text)
        create_sql = f"drop table if exists {self.t_name};" \
            f"drop tablespace if exists {self.ts_name};" \
            f"create tablespace {self.ts_name} relative location " \
            f"'{self.ts_name}';"
        msg = self.pri_sh.execut_db_sql(create_sql, sql_type='-C')
        self.log.info(msg)
        self.assertIn(self.constant.TABLESPCE_CREATE_SUCCESS, msg,
                      '执行失败:' + text)

        text = '-----step4:创建二级分区表，指定非分区列加密 expect:合理报错-----'
        self.log.info(text)
        create_sql = f"create table if not exists {self.t_name}(col_1 int ," \
            f"col_2 int ,col_3 varchar2 ( 30 )  encrypted with (column_" \
            f"encryption_key = {self.cek},encryption_type = deterministic)," \
            f"col_4 int ) tablespace {self.ts_name} " \
            f"partition by range (col_1) subpartition by range (col_2) " \
            f"( partition p_range_1 values less than(10) " \
            f"  ( subpartition p_range_1_1 values less than(5)," \
            f"    subpartition p_range_1_2 values less than(maxvalue)), " \
            f"  partition p_range_2 values less than(20) " \
            f"  ( subpartition p_range_2_1 values less than(5), " \
            f"    subpartition p_range_2_2 values less than(maxvalue)) " \
            f") enable row movement; "
        msg = self.pri_sh.execut_db_sql(create_sql, sql_type='-C')
        self.log.info(msg)
        self.assertIn(self.constant.NOT_YET_SUPPORTED_TYPE, msg,
                      '执行失败:' + text)

        text = '-----step5:创建二级分区表，指定分区列加密 expect:合理报错-----'
        self.log.info(text)
        create_sql = f"create table if not exists {self.t_name}(col_1 int ," \
            f"col_3 varchar2 ( 30 ),col_2 int encrypted with (column_" \
            f"encryption_key = {self.cek},encryption_type = deterministic)," \
            f"col_4 int ) tablespace {self.ts_name} " \
            f"partition by range (col_1) subpartition by range (col_2) " \
            f"( partition p_range_1 values less than(10) " \
            f"  ( subpartition p_range_1_1 values less than(5)," \
            f"    subpartition p_range_1_2 values less than(maxvalue)), " \
            f"  partition p_range_2 values less than(20) " \
            f"  ( subpartition p_range_2_1 values less than(5), " \
            f"    subpartition p_range_2_2 values less than(maxvalue)) " \
            f") enable row movement; "
        msg = self.pri_sh.execut_db_sql(create_sql, sql_type='-C')
        self.log.info(msg)
        self.assertIn(self.constant.NOT_YET_SUPPORTED_TYPE, msg,
                      '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step6:清理环境-----')
        text_1 = '-----删除表和密钥 expect:成功-----'
        self.log.info(text_1)
        drop_cmd = f'drop column encryption key {self.cek} cascade;' \
            f'drop client master key {self.cmk} cascade;' \
            f'drop table if exists {self.t_name};' \
            f'drop tablespace if exists {self.ts_name};'
        drop_msg = self.pri_sh.execut_db_sql(drop_cmd, sql_type='-C')
        self.log.info(drop_msg)

        text_2 = '-----恢复配置文件 expect:成功-----'
        self.log.info(text_2)
        del_cmd = f'if [[ -e {self.env_bak} && -e {macro.DB_ENV_PATH} ]]; ' \
            f'then rm -rf {macro.DB_ENV_PATH}; ' \
            f'mv {self.env_bak} {macro.DB_ENV_PATH}; ' \
            f'else echo not exits; fi'
        env_res = self.common.get_sh_result(self.primaryNode, del_cmd)

        text_3 = '-----删除密钥路径 expect:成功-----'
        self.log.info(text_3)
        rm_cmd = f'rm -rf {self.mkdir_path}'
        self.common.get_sh_result(self.primaryNode, rm_cmd)
        check_cmd = f'if [ -d {self.mkdir_path} ]; ' \
            f'then echo "exists"; else echo "not exists"; fi'
        rm_msg = self.common.get_sh_result(self.primaryNode, check_cmd)

        self.assertIn(self.constant.drop_cmk_success, drop_msg,
                      '执行失败:' + text_1)
        self.assertIn(self.constant.drop_cek_success, drop_msg,
                      '执行失败:' + text_1)
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, drop_msg,
                      '执行失败:' + text_1)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_msg,
                      '执行失败:' + text_1)
        self.assertEqual('', env_res, '执行失败:' + text_2)
        self.assertEqual('not exists', rm_msg, '执行失败:' + text_3)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
